from flask import Flask, request, jsonify, render_template
import json
import subprocess
import threading
import os
import requests
from datetime import datetime
import logging
from logging.handlers import RotatingFileHandler
import time

app = Flask(__name__)
app.json.ensure_ascii = False
webhook = os.getenv('WEBHOOK', 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2a07a707-af1b-4223-af6e-b2fbbfb8c3c1')
harbor_front = os.getenv('HARBOR_FRONT', 'reg.llschain.com')
harbor_user = os.getenv('HARBOR_HARBOR_USER', 'lls')
harbor_passwd = os.getenv('HARBOR_PASSWD', 'Lls@harbor123!')
skip_ip = os.getenv('LOCALHOSTIP', '172.16.129.39')
images_file = os.getenv('IMAGE_FILE', '/opt/images.tar')
# 配置日志
log_file = f"app.log"
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        RotatingFileHandler(log_file, maxBytes=1024*1024*5, backupCount=3),
        logging.StreamHandler()
    ]
)
@app.route('/')
def index():
    return render_template('index.html') 

@app.route('/pullforstr', methods=['POST'])
def pullforstr():
    data = request.form.get('images', '')
    if not data:
        message = "未正确传入镜像"
        logging.error(message)
        return  jsonify({"error": message}), 400
    images = data.split(',')
    with open('images.json', 'w') as f:
        json.dump({"images": images}, f, indent=4)
    threading.Thread(target=run_ansible).start()
    time.sleep(0.5)
    return jsonify({"message": "任务处理中, 后续会通过企业微信机器人通知执行情况, 请等待..."}), 202


@app.route('/pullforjson', methods=['POST'])
def pullforjson():
    data = request.json
    app_name = data["application"]
    images = []
    for service in data["services"]:
        service_name = service["service"]
        tag = service["tag"]
        image_name = f"{harbor_front}/{app_name}/{service_name}:{tag}"
        images.append(image_name)
    with open('images.json', 'w') as f:
        # f.write(f'{{ "images": {images} }}')
        json.dump({"images": images}, f, indent=4)
    threading.Thread(target=run_ansible).start()
    time.sleep(0.5)
    return jsonify({"message": "任务处理中, 后续会通过企业微信机器人通知执行情况, 请等待..."}), 202

def run_ansible():
    try:
        subprocess.run(['ansible-playbook', 'prepull.yml', '-e', f'images_file={images_file}', '-e', f'skip_ip={skip_ip}','-e', '@images.json', '-e', f'webhook={webhook}', '-e', f'docker_registry={harbor_front}', '-e', f'docker_username={harbor_user}', '-e', f'docker_password={harbor_passwd}' ], check=True, stderr=subprocess.PIPE)
    except subprocess.CalledProcessError as e:
        start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        error_message = e.stderr.decode('utf-8') 
        logging.warning(f"命令执行失败:\n  错误信息: {error_message}")
        markdown = f"**任务说明**: <font color=\"warning\">任务执行失败</font>\n**具体原因**: {error_message} 详情查看日志\n**任务开始时间**: {start_time}"
        payload = {
            "msgtype": "markdown",
            "markdown": {
                "content": markdown
            }
        }
        requests.post(webhook, json=payload, timeout=10)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)
